//
//  GlobalInterceptor.swift
//  全局拦截
//
//  Created by mini on 2025/4/28.
//

import Alamofire
import Foundation

// 全局拦截器
class GlobalInterceptor: NetworkInterceptor {

    // 添加请求计数器
    private var requestCount: Int = 0
    private let lock = NSLock()

    init() {}

    func interceptor(allow _: BaseRequest) -> Bool {
        return true
    }

    // 添加公共参数
    func interceptor(_ request: BaseRequest, parameter: Parameters?) -> Parameters? {
        let para: [String: Any] = parameter ?? [String: Any]()
        // para["public"] = "test"
        if request.method == .get {
            return nil
        }
        return para
    }

    // 添加公共请求头
    func interceptor(_ request: BaseRequest, headerFields: Alamofire.HTTPHeaders?) -> Alamofire.HTTPHeaders? {
        var header = HTTPHeaders()
        headerFields?.dictionary.forEach { header.add(name: $0.key, value: $0.value) }
        
        if request.path.contains("/Farmer/dull") {
            header.add(name: "Content-Type", value: "multipart/form-data")
        }else{
            header.add(name: "Content-Type", value: "application/x-www-form-urlencoded")
        }
        
        return header
    }

    // 请求开始。可配置显示加载指示器
    func interceptor(start request: BaseRequest) {
        // print("Request start: \(request.url)")
        if request.showLoading {
            lock.lock()
            requestCount += 1
            let shouldShow = requestCount == 1
            lock.unlock()
            if shouldShow {
                GlobalMethod.showLoadingView()
            }
        }
    }

    // 请求结束。可配置隐藏加载指示器
    func interceptor(end request: BaseRequest) {
        // print("Request end: \(request.url)")
        if request.showLoading {
            lock.lock()
            requestCount -= 1
            let shouldHide = requestCount == 0
            lock.unlock()
            if shouldHide {
                GlobalMethod.hideLoadingView()
            }
        }
    }
}
